import json

import requests
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.views import AuthorizationView

from oauth.common.RsaCommon import RsaCommon
from user.views import _register_user


def home(request):
	params = {}
	return render(request, 'index.html', params)


@csrf_exempt
def get_token(request):
	'''
    由于baidu发送post请求格式不正确，post参数直接写在URL上，导致 oauth server 获取不到post数据，这个方法用来重写这个过程
    发送post请求
    :param request:
    :return:
    '''
	dataParam = len(request.GET) > 0 and request.GET or request.POST
	url = request.build_absolute_uri(reverse("oauth2_provider:token"))
	# return HttpResponse({}, content_type="application/json")
	headers = {'content-type': 'application/x-www-form-urlencoded', 'cache-control': "no-cache"}
	response = requests.post(url, data=dataParam, headers=headers)
	# response = requests.request("POST", url, data=dataParam, headers=headers)
	return HttpResponse(response, content_type="application/json")


class AuthorizationViewCustom(AuthorizationView):
	'''自定义Class'''

	def dispatch(self, request, *args, **kwargs):
		print("自定义Class 用来解决一键登录问题")
		# 判断用户是否为一键登录，如果为一键登录，则自动登录成功
		en_phone = request.GET.get('phone', '')
		if en_phone:
			_rsa = RsaCommon()
			phone = _rsa.decrypt(en_phone)
			# print(phone)
			_reg_ret = _register_user(phone=phone)
			if _reg_ret['retcode'] == 'SUCC':
				_user = User.objects.get(username=phone)
				auth.login(request, _user)

		# <<
		return super().dispatch(request, *args, **kwargs)
